package com.zm.schedule.schedulemgr.listener;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
import java.util.Date;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;

import com.zm.base.core.exception.BaseException;
import com.zm.schedule.schedulemgr.po.TbZmScheduleJob;
import com.zm.schedule.schedulemgr.po.TbZmScheduleJobLog;
import com.zm.schedule.schedulemgr.service.IScheduleService;

/**
 * @author chenhuaming
 * @Time：2017年5月10日 上午9:54:03
 * @version 1.0
 */
public class ZMScheduleListener implements JobListener {
	private static Logger logger = Logger.getLogger(ZMScheduleListener.class);
	@Resource(name="scheduleService")
	private IScheduleService scheduleService;

	@Override
	public String getName() {
		
		return "ZMScheduleListener";
	}

	@Override
	public void jobExecutionVetoed(JobExecutionContext context) {

	}

	@Override
	public void jobToBeExecuted(JobExecutionContext context) {
		try {
			TbZmScheduleJob scheduleJob = (TbZmScheduleJob) context.getMergedJobDataMap().get("scheduleJob");
			scheduleService.updateJobStatusByJobName("2",scheduleJob.getJobName());
		    } catch (SQLException e) {
		      logger.error("更新任务状态时发生异常", e);
		    } catch (BaseException e) {
		    	logger.error("更新任务状态时发生异常", e);
				e.printStackTrace();
			} catch (Exception e) {
				logger.error("更新任务状态时发生异常", e);
				e.printStackTrace();
			}
	}

	@Override
	public void jobWasExecuted(JobExecutionContext jobExecutionContext,
			JobExecutionException e) {
		TbZmScheduleJobLog jobLogPO = new TbZmScheduleJobLog();
		TbZmScheduleJob scheduleJob = (TbZmScheduleJob) jobExecutionContext.getMergedJobDataMap().get("scheduleJob");
	    jobLogPO.setJobName(scheduleJob.getJobName());
	    jobLogPO.setStartDate(jobExecutionContext.getFireTime());
	    jobLogPO.setCompleteDate(new Date());
	    if (null != e) {
	      jobLogPO.setExecuteResult(Integer.valueOf(1));
	      jobLogPO.setExecuteException(getStrForStackTrace(e));
	      logger.info("任务" + scheduleJob.getJobName() + "运行时发生异常", e);
	    } else {
	      jobLogPO.setExecuteResult(Integer.valueOf(0));
	    }
	    try {
	    	jobLogPO.setLogId(UUID.randomUUID().toString());
	    	scheduleService.saveTbZmScheduleJobLog(jobLogPO);
	    	scheduleService.updateJobStatusByJobName("2",scheduleJob.getJobName());
	    } catch (Exception e1) {
	      logger.error(e1.getMessage(), e1);
	    } 

	}
	private static String getStrForStackTrace(Exception e)
	  {
	    if (e == null)
	      return null;
	    StringWriter sw = new StringWriter();
	    e.printStackTrace(new PrintWriter(sw, true));
	    return sw.toString();
	  }
}
